import pandas as pd
from sklearn.preprocessing import OneHotEncoder

pd_data_raw = pd.DataFrame({
    'col1': ['good', 'good', 'bad'],
    'col2': [4, 5, 6],
    'col3': [0, 1, 0],
    'y': [0, 1, 1]
})


def one_hot(series):
    oe = OneHotEncoder()
    trans = oe.fit_transform(series.values.reshape(-1, 1)).toarray()
    len_categories = len(oe.categories_[0])
    trans_dict = {}
    for n, i in enumerate(oe.categories_[0]):
        background = ['0'] * len_categories
        background[n] = '1'
        trans_dict.update({i: ''.join(background)})
    return trans, trans_dict


def transform(col_li, pd_data):
    for k in col_li:
        trans_data, trans_dict = one_hot(pd_data[k])
        for n, i in enumerate(trans_dict.keys()):
            pd_data[f'{k}_{i}'] = trans_data[:, n]
        pd_data = pd_data.drop(k, axis=1)
    return pd_data


print('原始数据:\n', pd_data_raw)

headers = ['col1', 'col2', 'col3']

pd_data_trans = transform(headers, pd_data_raw)
print('热编码后数据:\n', pd_data_trans)
